package com.isoft.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isoft.entity.DmUser;
import com.isoft.entity.LoginRequest;
import com.isoft.entity.ChangePasswordRequest;
import com.isoft.result.R;
import com.isoft.service.DmUserService;
import com.isoft.service.CaptchaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private DmUserService dmUserService;

    @Autowired
    private CaptchaService captchaService;

    @RequestMapping("/test")
    public String getUser() {
        return "get user";
    }

    // 登录（带验证码校验）
    @RequestMapping("/login")
    public R login(@RequestBody LoginRequest loginRequest, HttpSession session) {
        // 验证验证码
        if (loginRequest.getCaptchaId() == null || loginRequest.getCaptchaCode() == null) {
            return R.error("验证码不能为空");
        }

        boolean captchaValid = captchaService.validateCaptcha(loginRequest.getCaptchaId(), loginRequest.getCaptchaCode());
        if (!captchaValid) {
            return R.error("验证码错误或已过期");
        }

        // 验证用户名密码
        DmUser user = new DmUser();
        user.setUserName(loginRequest.getUsername());
        user.setPassword(loginRequest.getPassword());

        DmUser loginUser = dmUserService.login(user);
        if (loginUser == null) {
            return R.error("用户名或密码错误");
        }

        // 登录成功，保存用户对象到Session
        session.setAttribute("currentUser", loginUser);
        return R.ok(loginUser);
    }

    // 注册
    @RequestMapping("/register")
    public R register(@RequestBody DmUser user) {
        // 根据用户名查询\

        DmUser u = dmUserService.getOne(new QueryWrapper<DmUser>().eq("user_name", user.getUserName()));
        if (u != null){
            return R.ok(false);
        }
        user.setStatus("ACTIVE");
        return R.ok(dmUserService.save(user));
    }

    /**
     * 分页查询用户信息
     */
    @GetMapping("/page")
    public R getPage(@RequestParam(defaultValue = "1") Integer current,
                     @RequestParam(defaultValue = "10") Integer size,
                     @RequestParam(required = false) String userId,
                     @RequestParam(required = false) String userName,
                     @RequestParam(required = false) String email,
                     @RequestParam(required = false) String phone,
                     @RequestParam(required = false) String status,
                     @RequestParam(required = false) String role) {
        Page<DmUser> page = new Page<>(current, size);
        QueryWrapper<DmUser> queryWrapper = new QueryWrapper<>();

        if (userId != null && !userId.isEmpty()) {
            queryWrapper.like("user_id", userId);
        }
        if (userName != null && !userName.isEmpty()) {
            queryWrapper.like("user_name", userName);
        }
        if (email != null && !email.isEmpty()) {
            queryWrapper.like("email", email);
        }
        if (phone != null && !phone.isEmpty()) {
            queryWrapper.like("phone", phone);
        }
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }
        if (role != null && !role.isEmpty()) {
            queryWrapper.eq("role", role);
        }

        IPage<DmUser> pageResult = dmUserService.page(page, queryWrapper);
        return R.ok(pageResult);
    }

    /**
     * 获取所有用户信息
     */
    @GetMapping("/list")
    public R getList() {
        List<DmUser> list = dmUserService.list();
        return R.ok(list);
    }

    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id) {
        DmUser user = dmUserService.getById(id);
        return R.ok(user);
    }

    /**
     * 新增用户信息
     */
    @PostMapping
    public R save(@RequestBody DmUser user) {
        // 检查用户名是否已存在
        DmUser existUser = dmUserService.getOne(new QueryWrapper<DmUser>().eq("user_name", user.getUserName()));
        if (existUser != null) {
            return R.error("用户名已存在");
        }

        // 检查用户ID是否已存在
        if (user.getUserId() != null) {
            DmUser existUserById = dmUserService.getOne(new QueryWrapper<DmUser>().eq("user_id", user.getUserId()));
            if (existUserById != null) {
                return R.error("用户ID已存在");
            }
        }

        // 设置默认角色
        if (user.getRole() == null || user.getRole().isEmpty()) {
            user.setRole("USER");
        }

        // 设置默认状态
        if (user.getStatus() == null || user.getStatus().isEmpty()) {
            user.setStatus("ACTIVE");
        }

        boolean result = dmUserService.save(user);
        return result ? R.ok("新增成功") : R.error("新增失败");
    }

    /**
     * 更新用户信息
     */
    @PutMapping
    public R update(@RequestBody DmUser user) {
        boolean result = dmUserService.updateById(user);
        return result ? R.ok("更新成功") : R.error("更新失败");
    }

    /**
     * 修改用户角色
     */
    @PutMapping("/role")
    public R updateUserRole(@RequestParam Long userId, @RequestParam String role) {
        DmUser user = dmUserService.getById(userId);
        if (user == null) {
            return R.error("用户不存在");
        }

        user.setRole(role);
        boolean result = dmUserService.updateById(user);
        return result ? R.ok("角色修改成功") : R.error("角色修改失败");
    }

    /**
     * 根据用户名获取用户信息
     */
    @GetMapping("/info")
    public R getUserByUsername(@RequestParam String username) {
        DmUser user = dmUserService.getOne(new QueryWrapper<DmUser>().eq("user_name", username));
        if (user == null) {
            return R.error("用户不存在");
        }
        // 不返回密码信息
        user.setPassword(null);
        return R.ok(user);
    }

    /**
     * 获取当前用户信息（需要从session或token中获取用户身份）
     */
    @GetMapping("/current")
    public R getCurrentUser(@RequestParam(required = false) String username) {
        if (username == null || username.isEmpty()) {
            return R.error("用户名不能为空");
        }

        DmUser user = dmUserService.getOne(new QueryWrapper<DmUser>().eq("username", username));
        if (user == null) {
            return R.error("用户不存在");
        }
        // 不返回密码信息
        user.setPassword(null);
        return R.ok(user);
    }

    /**
     * 删除用户信息
     */
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        boolean result = dmUserService.removeById(id);
        return result ? R.ok("删除成功") : R.error("删除失败");
    }

    /**
     * 批量删除用户信息
     */
    @DeleteMapping("/batch")
    public R deleteBatch(@RequestBody List<Long> ids) {
        boolean result = dmUserService.removeByIds(ids);
        return result ? R.ok("批量删除成功") : R.error("批量删除失败");
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public R changePassword(@RequestBody ChangePasswordRequest req) {
        // 1. 校验参数
        if (req.getId() == null || req.getOriginalPassword() == null || req.getNewPassword() == null) {
            return R.error("参数不能为空");
        }
        if (req.getNewPassword().length() < 8 || req.getNewPassword().length() > 12) {
            return R.error("新密码长度需8-12位");
        }
        // 2. 查询用户
        DmUser user = dmUserService.getById(req.getId());
        if (user == null) {
            return R.error("用户不存在");
        }
        if (!user.getPassword().equals(req.getOriginalPassword())) {
            return R.error("原密码错误");
        }
        // 3. 修改密码
        user.setPassword(req.getNewPassword());
        boolean result = dmUserService.updateById(user);
        return result ? R.ok("密码修改成功") : R.error("密码修改失败");
    }
}
